package icu.groot.alan.hotel.util.interceptor;

import icu.groot.alan.hotel.util.BizException;
import icu.groot.alan.hotel.util.GrootApi;
import icu.groot.alan.hotel.util.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;

@Component
@Slf4j
public class IdentityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("进入Identity拦截器: preHandle");
        String token = request.getHeader(GrootApi.Jwt.HEADER);
        try {
            GrootApi.Jwt.validate(token);
        }catch (Exception e){
            throw new BizException(ResultCodeEnum.TOKEN_FAILED);
        }
        LinkedList<String> validate = GrootApi.Jwt.validate(token);
        response.setHeader(GrootApi.Jwt.HEADER, validate.get(0));
        request.setAttribute(GrootApi.Jwt.HEADER, validate.get(1));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("进入Identity拦截器: postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("进入Identity拦截器: afterCompletion");
    }
}
